<template>
  <div class="draw-wrapper">
    <span class="comp-title">检测区域绘制</span>
    <div
      class="image-wrapper"
      :style="{
        width: wrapperWidth + 'px',
        height: wrapperHeight + 'px',
      }"
    >
      <div ref="backImageRef" class="back-image"></div>
      <div
        class="draw-content-wrapper"
        :style="{
          width: drawWidth + 'px',
          height: drawHeight + 'px',
        }"
        v-if="showDrawComp"
      >
        <drawPolygonsComp
          class="draw-comp"
          ref="drawCompRef"
          :canvasWidth="drawWidth"
          :canvasHeight="drawHeight"
          :naturalWidth="naturalWidth"
          :naturalHeight="naturalHeight"
          :style="{
            zIndex: drawType === drawTypeEnum.polygons ? 1 : 0,
          }"
          :polygons="polygons"
          :pointItemIsObj="pointItemIsObj"
          :editable="false"
          :judgePointIsIntersect="judgePointIsIntersect"
          :faultTolerant="10"
          @pointIsIntersect="pointIsIntersect"
        />
        <drawLineComp
          class="draw-comp"
          ref="drawLineCompRef"
          :canvasWidth="drawWidth"
          :canvasHeight="drawHeight"
          :naturalWidth="naturalWidth"
          :naturalHeight="naturalHeight"
          :style="{
            zIndex: drawType === drawTypeEnum.lines ? 1 : 0,
          }"
          :lines="lines"
          :pointItemIsObj="pointItemIsObj"
          :editable="false"
          :judgeIsOverlapping="judgeIsOverlapping"
          :faultTolerant="10"
          @pointIsIntersect="pointIsIntersect"
        />
      </div>
    </div>
    <div class="operate-wrapper">
      <a-button
        v-for="(item, index) in operateList"
        :key="index"
        :type="
          item.highlight && operateType === item.value ? 'primary' : 'default'
        "
        @click="changeOperateType(item.value)"
        >{{ item.label }}</a-button
      >
    </div>
    <p>提示：您可使用鼠标在图片上绘制出布防区域。</p>
  </div>
</template>
<script setup>
import { computed, onMounted, ref, nextTick, onUnmounted } from "vue";
import drawPolygonsComp from "./drawPolygons.vue";
import drawLineComp from "./drawLine.vue";
import {
  arrDicFind,
  convertByRatio,
  debounce,
  getNetworkInterfaces,
} from "@/utils/index.js";
import { drawTypeEnum } from "@/constant/dictionary";
const emits = defineEmits(["changeModalInfo"]);
const defaultWidth = ref(800);
const defaultHeight = ref(450);
const proportion = ref(defaultWidth.value / defaultHeight.value);
// 播放窗口大小（不等于播放画面大小
const wrapperWidth = ref(defaultWidth.value);
const wrapperHeight = ref(defaultHeight.value);
// 绘制窗口大小（等于播放画面大小
const drawWidth = ref(defaultWidth.value);
const drawHeight = ref(defaultHeight.value);
const backImageRef = ref(null);
const drawCompRef = ref(null);
const drawLineCompRef = ref(null);
const showDrawComp = ref(false);

const naturalWidth = ref(null);
const naturalHeight = ref(null);
const pointItemIsObj = ref(true);
// 多边形允许交叉
const judgePointIsIntersect = ref(false);
// 线段允许交叉
const judgeIsOverlapping = ref(false);
const propsVal = defineProps({
  coordinatesData: {
    type: Object,
    default: null,
  },
  deviceInfo: {
    type: Object,
    default: null,
  },
  subscribeId: {
    type: String,
    default: null,
  },
  playUrl: {
    type: String,
    default: null,
  },
});
const drawType = ref(drawTypeEnum.polygons);
const lines = computed(() => {
  return getPointList(propsVal.coordinatesData?.lines || [], false);
});
const polygons = computed(() => {
  return getPointList(propsVal.coordinatesData?.polygons || [], false);
});
onMounted(() => {
  window.onresize = resizeCb;
  testImage();
});
onUnmounted(() => {
  window.onresize = null;
});
const resizeCb = (isResize = true) => {
  // 刷新画布的展示
  refreshCanRectData(isResize);
  wrapperHeight.value = document.body.clientHeight / 2;
  if (wrapperHeight.value * proportion.value >= 450) {
    wrapperWidth.value = wrapperHeight.value * proportion.value;
  }
  emits("changeModalInfo", {
    width: wrapperWidth.value + 64 + "px",
  });
  if (defaultHeight.value > wrapperHeight.value) {
    refreshDrawRectZoo(
      wrapperWidth.value * proportion.value,
      wrapperHeight.value,
      proportion.value
    );
  } else {
    refreshDrawRectZoo(
      wrapperWidth.value,
      wrapperHeight.value,
      proportion.value
    );
  }
};
const refreshCanRectData = debounce(function (isResize) {
  drawCompRef.value?.init(isResize);
  drawLineCompRef.value?.init(isResize);
}, 200);

const operateList = computed(() => {
  return [
    {
      label: "全部区域",
      value: 0,
    },
    {
      label: "添加多边形框",
      value: 1,
      highlight: true,
    },
    {
      label: "添加线段",
      value: 2,
      highlight: true,
    },
    {
      label: "清除",
      value: 3,
    },
    // {
    //   label: "DeletePrevious",
    //   value: 4,
    // },
    {
      label: `${(drawType.value === drawTypeEnum.lines ? judgeIsOverlapping.value : judgePointIsIntersect.value) ? '不' : ''}允许交叉`,
      value: 5,
    },
  ];
});
const pointIsIntersect = () => {
  console.log("pointIsIntersect");
};
const operateType = ref(null);
// isCallBack是否自动调用回调
const changeOperateType = (value, isCallBack = false) => {
  const oldVal = operateType.value;
  operateType.value = value;
  switch (value) {
    case 0:
      drawCompRef.value.ClickClear();
      drawCompRef.value.drawFullScreen();
      if (oldVal === 2) {
        changeOperateType(oldVal, true);
      } else {
        drawCompRef.value.disabledDraw();
      }
      break;
    case 1:
      drawType.value = drawTypeEnum.polygons;
      // 手动触发需要清空全屏状态多边形
      !isCallBack && drawCompRef.value.deleteFullScreen();
      drawCompRef.value.ClickDraw();
      break;
    case 2:
      drawType.value = drawTypeEnum.lines;
      drawLineCompRef.value.ClickDraw();
      break;
    case 3:
      drawCompRef.value.ClickClear();
      drawLineCompRef.value.ClickClear();
      if (oldVal === 1 || oldVal === 2) {
        changeOperateType(oldVal, true);
      }
      break;
    case 4:
      if (drawType.value === drawTypeEnum.lines) {
        drawLineCompRef.value.DeletePrevious();
      } else {
        drawCompRef.value.DeletePrevious();
      }
      if (oldVal === 1 || oldVal === 2) {
        changeOperateType(oldVal, true);
      }
      break;
    case 5:
      if (drawType.value === drawTypeEnum.lines) {
        judgeIsOverlapping.value = !judgeIsOverlapping.value;
      } else {
        judgePointIsIntersect.value = !judgePointIsIntersect.value;
      }
      break;
    default:
      break;
  }
};
// 重新获取绘制区域大小
const refreshDrawRectZoo = (width, height, widthPropHeight = 1) => {
  if (widthPropHeight <= 1) {
    // 比例高度大于比例宽度
    drawHeight.value = convertByRatio(width, widthPropHeight);
    if (drawHeight.value > height) {
      drawHeight.value = height;
    }
    drawWidth.value = convertByRatio(drawHeight.value, 1 / widthPropHeight);
  } else {
    // 比例宽度大于比例高度
    drawWidth.value = convertByRatio(height, widthPropHeight);
    if (drawWidth.value > width) {
      drawWidth.value = width;
    }
    drawHeight.value = convertByRatio(drawWidth.value, 1 / widthPropHeight);
  }
  // naturalWidth.value = backImageRef.value.naturalWidth;
  // naturalHeight.value = backImageRef.value.naturalHeight;
  naturalWidth.value = drawWidth.value;
  naturalHeight.value = drawHeight.value;
};
const drawCompInit = (params) => {
  const { codecWidth, codecHeight } = params || {};
  console.log(codecWidth, codecHeight, "codecWidth, codecHeight");
  if (codecHeight && codecWidth) {
    proportion.value = codecWidth / codecHeight;
    resizeCb(false);
  }
  showDrawComp.value = true;
  nextTick(() => {
    // 如果存在全部区域就禁止绘多边形
    drawCompRef.value &&
      polygons.value.some(drawCompRef.value.judgeIsFullScreen);
  });
};
const testImage = () => {
  drawCompInit({
    codecWidth: 16000,
    codecHeight: 9000,
  });
};
const handleSave = () => {
  return Promise.all([
    drawLineCompRef.value?.ClickPut(),
    drawCompRef.value?.ClickPut(),
  ]).then((res) => {
    return res.map((pointArrGroup) => {
      return getPointList(pointArrGroup);
    });
  });
};
const getSavePoint = (arr, isSave) => {
  return arr.map((pointValue) => [
    convertByRatio(
      pointValue[0],
      {
        now: isSave ? 10000 : drawWidth.value,
        old: isSave ? drawWidth.value : 10000,
      },
      { isInt: isSave }
    ),
    convertByRatio(
      pointValue[1],
      {
        now: isSave ? 10000 : drawHeight.value,
        old: isSave ? drawHeight.value : 10000,
      },
      { isInt: isSave }
    ),
  ]);
};
const getPointList = (pointArrGroup, isSave = true) => {
  return pointItemIsObj.value
    ? pointArrGroup.map((pointObj) => {
        return {
          ...(pointObj || null),
          id: pointObj?.id ?? getNetworkInterfaces(),
          name: "",
          positions: getSavePoint(pointObj.positions || [], isSave),
        };
      })
    : pointArrGroup.map((pointArr) => {
        return getSavePoint(pointArr, isSave);
      });
};
defineExpose({
  handleSave,
});
</script>
<style lang="scss" scoped>
.draw-wrapper {
  width: 100%;
  padding: 16px 32px 12px;
  font-size: 14px;
  text-align: left;
  font-weight: 400;
  line-height: 22px;
  .comp-title {
    color: #666666;
  }
  .image-wrapper {
    margin: 8px 0 16px;
    position: relative;
    .draw-content-wrapper {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      > .draw-comp {
        position: absolute;
        left: 0;
        top: 0;
      }
    }
    > .back-image {
      width: 100%;
      height: 100%;
      background-color: #fcd;
    }
  }
  .operate-wrapper {
    > button {
      margin-right: 16px;
    }
  }
  > p {
    margin: 7px 0 0;
    color: #999999;
  }
}
</style>
